package com.zb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.ZjWorkSpareLog;
import com.zb.entity.ZjWorkSpareLogImage;
import com.zb.list.WorkSpareLogListVo;
import com.zb.mapper.ZjWorkSpareLogMapper;
import com.zb.result.PageUtil;
import com.zb.service.ZjWorkSpareLogImageService;
import com.zb.service.ZjWorkSpareLogService;
import com.zb.utils.TransactionUtil;
import com.zb.utils.ZbManager;
import com.zb.vo.WorkSpareLogVo;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 工单备件记录表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-10-27
 */
@Service
public class ZjWorkSpareLogServiceImpl extends ServiceImpl<ZjWorkSpareLogMapper, ZjWorkSpareLog> implements ZjWorkSpareLogService {
    @Resource(name = "asyncServiceExecutor")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Resource
    private PlatformTransactionManager platformTransactionManager;
    @Resource
    private ZjWorkSpareLogImageService workSpareLogImageService;


    // 保存客服操作的工单备件记录
    @Override
    public void saveServiceWorkSpareLog(WorkSpareLogVo workSpareLogVo) {
        List<WorkSpareLogVo> workSpareLogVos = new ArrayList<>();
        workSpareLogVos.add(workSpareLogVo);
        saveServiceWorkSpareLog(workSpareLogVos);
    }

    // 批量保存客服操作的工单备件记录
    @Override
    public void saveServiceWorkSpareLog(List<WorkSpareLogVo> workSpareLogVos) {
        if (CollectionUtil.isEmpty(workSpareLogVos)) {
            return;
        }
        List<ZjWorkSpareLog> logs = new ArrayList<>();
        List<ZjWorkSpareLogImage> images = new ArrayList<>();
        getSpareLogData(1,1, logs, images, workSpareLogVos);
        save(logs, images);
    }

    // 保存移动端网点操作的工单备件记录
    @Override
    public void saveMobileNetworkWorkSpareLog(WorkSpareLogVo workSpareLogVo) {
        List<WorkSpareLogVo> workSpareLogVos = new ArrayList<>();
        workSpareLogVos.add(workSpareLogVo);
        saveMobileNetworkWorkSpareLog(workSpareLogVos);
    }

    // 批量保存移动端网点操作的工单备件记录
    @Override
    public void saveMobileNetworkWorkSpareLog(List<WorkSpareLogVo> workSpareLogVos) {
        if (CollectionUtil.isEmpty(workSpareLogVos)) {
            return;
        }
        List<ZjWorkSpareLog> logs = new ArrayList<>();
        List<ZjWorkSpareLogImage> images = new ArrayList<>();
        getSpareLogData(1,2, logs, images, workSpareLogVos);
        save(logs, images);
    }

    // 保存第三方系统操作的工单备件记录
    @Override
    public void saveThirdSystemWorkSpareLog(WorkSpareLogVo workSpareLogVo) {
        List<WorkSpareLogVo> workSpareLogVos = new ArrayList<>();
        workSpareLogVos.add(workSpareLogVo);
        saveThirdSystemWorkSpareLog(workSpareLogVos);
    }

    // 批量保存第三方系统操作的工单备件记录
    @Override
    public void saveThirdSystemWorkSpareLog(List<WorkSpareLogVo> workSpareLogVos) {
        if (CollectionUtil.isEmpty(workSpareLogVos)) {
            return;
        }
        List<ZjWorkSpareLog> logs = new ArrayList<>();
        List<ZjWorkSpareLogImage> images = new ArrayList<>();
        getSpareLogData(1,3, logs, images, workSpareLogVos);
        save(logs, images);
    }

    // 保存客服操作的工单备件旧件记录
    @Override
    public void saveServiceWorkSpareOldLog(WorkSpareLogVo workSpareLogVo) {
        List<WorkSpareLogVo> workSpareLogVos = new ArrayList<>();
        workSpareLogVos.add(workSpareLogVo);
        saveServiceWorkSpareOldLog(workSpareLogVos);
    }

    // 保存客服操作的工单备件旧件记录
    @Override
    public void saveServiceWorkSpareOldLog(List<WorkSpareLogVo> workSpareLogVos) {
        if (CollectionUtil.isEmpty(workSpareLogVos)) {
            return;
        }
        List<ZjWorkSpareLog> logs = new ArrayList<>();
        List<ZjWorkSpareLogImage> images = new ArrayList<>();
        getSpareLogData(2,1, logs, images, workSpareLogVos);
        save(logs, images);
    }

    private void getSpareLogData(Integer type, Integer createEmpType, List<ZjWorkSpareLog> logs, List<ZjWorkSpareLogImage> images, List<WorkSpareLogVo> workSpareLogVos) {
        ZjWorkSpareLog log = null;
        ZjWorkSpareLogImage image = null;
        for (WorkSpareLogVo vo : workSpareLogVos) {
            log = new ZjWorkSpareLog();
            BeanUtil.copyProperties(vo, log);
            log.setId(IdWorker.getId());
            log.setType(type);
            log.setCreateEmpType(createEmpType);
            logs.add(log);
            if (CollectionUtil.isNotEmpty(vo.getImages())) {
                for (String s : vo.getImages()) {
                    image = new ZjWorkSpareLogImage();
                    image.setId(IdWorker.getId());
                    image.setCustAccId(log.getCustAccId());
                    image.setWorkSpareLogId(log.getId());
                    image.setImage(s);
                    images.add(image);
                }
            }
        }
    }

    private void save(List<ZjWorkSpareLog> logs, List<ZjWorkSpareLogImage> images) {
        threadPoolTaskExecutor.execute(() -> {
            TransactionStatus status = platformTransactionManager.getTransaction(TransactionUtil.transactionDefinition());
            try {
                this.saveBatch(logs);
                if (CollectionUtil.isNotEmpty(images)) workSpareLogImageService.saveBatch(images);
                platformTransactionManager.commit(status);
            }catch (Exception e) {
                platformTransactionManager.rollback(status);
                ZbManager.log.error("添加工单备件记录失败："+ e);
            }
        });
    }


    // 根据工单备件ID获取工单备件日志记录列表
    @Override
    public Map<String, Object> getOrderWorkSpareLogList(Long workSpareId, PageUtil pageUtil) {
        return getLogList(1, workSpareId, pageUtil);
    }

    // 根据工单备件旧件ID获取工单备件日志记录列表
    @Override
    public Map<String, Object> getOrderWorkOldSpareLogList(Long workOldSpareId, PageUtil pageUtil) {
        return getLogList(2, workOldSpareId, pageUtil);
    }

    private Map<String, Object> getLogList(Integer type, Long valId, PageUtil pageUtil) {
        PageUtil.setPageLimit(pageUtil);
        QueryWrapper<ZjWorkSpareLog> wrapper = new QueryWrapper<>();
        wrapper.select("id", "create_emp_type", "create_emp", "event", "content", "gmt_create");
        wrapper.eq("val_id", valId).eq("type", type);
        Page<ZjWorkSpareLog> page = this.page(new Page<>(pageUtil.getPage(), pageUtil.getLimit()), wrapper);

        List<Long> logIds = page.getRecords().stream().map(ZjWorkSpareLog::getId).toList();
        List<ZjWorkSpareLogImage> images = workSpareLogImageService.getByWorkSpareLogIds(logIds);

        List<WorkSpareLogListVo> voList = page.getRecords().stream().map(spare -> {
            WorkSpareLogListVo vo = new WorkSpareLogListVo();
            BeanUtil.copyProperties(spare, vo);
            vo.setCreateTime(spare.getGmtCreate());
            vo.setImages(images.stream().filter(f -> Objects.equals(f.getWorkSpareLogId(), spare.getId())).map(ZjWorkSpareLogImage::getImage).toList());
            return vo;
        }).toList();
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), voList);
    }
}
